package 哈希表;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author zxl
 * @Date 2022/1/17 20:43
 * @Desc 在数组中找到两个元素的数值之和为目标值，返回这两个元素的下标
 */
public class 两数之和 {

    public static void main(String[] args) {

        int[] nums = {2,7,11,15};
        int target = 9;
        Integer[] indexes = findSum(nums,target);
        System.out.println("目标元素下标：" + (indexes == null ? "NULL" : Arrays.toString(indexes)));

    }

    public static Integer[] findSum(int[] nums, int target){
        Map<Integer, Integer> numMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            Integer index = numMap.get(target - nums[i]);
            if (index == null){
                numMap.put(nums[i], i);
            }else{
                return new Integer[]{index,i};
            }
        }
        return null;
    }
}
